#!/bin/bash

# install_and_configure_sudo.sh
# 功能说明:
# 1. 为一个或多个用户安装 sudo 并配置免密码 sudo 权限。
# 2. 如果系统未安装 sudo，则提示用户输入 root 密码以安装。
# 3. 检查用户是否在 sudo 组中，如果不在则添加到 sudo 组。
# 4. 支持通过命令行参数传入用户名列表；如果未传入参数，则默认操作当前用户。
# 5. 自动检测用户是否已经具有免密码 sudo 权限，避免重复配置。
# 6. 仅允许非 root 用户执行脚本。

install_and_configure_sudo() {
  local user="$1"

  command="$(cat << EOF
# 检查并安装 sudo
if ! command -v sudo &>/dev/null; then
  echo "sudo is not installed. Installing sudo..."
  apt-get update && apt-get -y install sudo
else
  echo "sudo is already installed."
fi

# 检查用户是否在 sudo 组
if ! id -nG "$user" | grep -qw "sudo"; then
  echo "User $user is not in the sudo group. Adding to sudo group..."
  usermod -aG sudo "$user"
  echo "User $user has been added to the sudo group."
else
  echo "User $user is already in the sudo group."
fi

# 配置免密码 sudo
if grep -q "$user ALL=(ALL) NOPASSWD: ALL" /etc/sudoers; then
  echo "Passwordless sudo is already enabled for $user."
else
  echo "$user ALL=(ALL) NOPASSWD: ALL" | bash -c '(EDITOR="tee -a" visudo)'
  echo "Passwordless sudo has been enabled for $user."
fi
EOF
)"

  # 提示输入 root 密码并执行命令
  printf "Enter your root password to proceed: "
  su --preserve-environment -c "$command"
}

main() {
  # 确保脚本由非 root 用户执行
  if [[ $EUID -eq 0 ]]; then
    echo "This script must be run as a non-root user."
    exit 1
  fi

  # 如果没有提供用户名，则默认操作当前用户
  if [[ $# -eq 0 ]]; then
    echo "No usernames provided. Defaulting to the current user: $USER"
    install_and_configure_sudo "$USER"
  else
    # 遍历所有传入的用户名
    for user in "$@"; do
      if id "$user" &>/dev/null; then
        install_and_configure_sudo "$user"
      else
        echo "User $user does not exist on this system."
      fi
    done
  fi
}

# 执行主函数
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
  main "$@"
fi

